/*
 * @descripttion:
 * @author: cp
 * @Date: 2021-04-22 19:45:56
 */
const Koa = require('koa');
const path = require('path');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koaStatic = require('koa-static');

const { REDIS_CONF } = require('./conf/db');
const { SESSION_KEY } = require('./conf/secretKeys');

const index = require('./routes/index');
const user = require('./routes/user');
const utilsAPIRouter = require('./routes/utils');

// error handler
onerror(app);

// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text'],
  })
);
app.use(json());
app.use(logger());
app.use(koaStatic(__dirname + '/public'));
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')));

app.use(
  views(__dirname + '/views', {
    extension: 'ejs',
  })
);

// session 配置
app.keys = [SESSION_KEY];
app.use(
  session({
    key: 'weibo.sid', // cookie name 默认是 'koa.sid'
    prefix: 'weibo:sess:', // redis key的前缀， 默认是： 'koa:sess:'
    cookie: {
      path: '/',
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
    },
    store: redisStore({
      all: `${REDIS_CONF.host}:${REDIS_CONF.port}`,
    }),
  })
);

// routes
app.use(index.routes(), index.allowedMethods());
app.use(user.routes(), user.allowedMethods());
app.use(utilsAPIRouter.routes(), utilsAPIRouter.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

module.exports = app;
